<?php

namespace App\Http\Controllers\Guard\Car;

use App\Http\Controllers\Common\GuardController;
use App\Models\Car\CarInfo;
use App\Models\Car\Order;
use App\Models\Car\RentUnit;
use App\Models\Constant\CarConstant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends GuardController {


    public function __construct() {
        $this->instance = new Order();
    }

    public function lst(Request $request) {
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);
        $conditions = $request->input();
        $records = $this->instance->getLst($conditions)->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());

    }

    public function getFreeCarLst(Request $request){
        $records = (new CarInfo())->getFreeCars();
        return responseSuccess($records->toArray());
    }

    //编辑订单时需要用所有车辆列表
    public function getAllCarLst(Request $request){
        $records = (new CarInfo())->getAllCars();
        return responseSuccess($records->toArray());
    }

    public function add(Request $request) {
        $info = $request->input();
        $this->validate($request, [
            'required'=>'rent_unit_id|rent_time|select_car_ids'
        ],[],[
            'select_car_ids'=>'车辆',
            'rent_unit_id'=>'外租单位',
            'rent_time'=>'派车时间'
        ]);
        //dd($info);
        $rentUnitId = $info['rent_unit_id'];
        $rentUnit = RentUnit::query()->where('id',$rentUnitId)->first();
        if (empty($rentUnit))return responseFail('外租单位不能为空！');
        try {
            DB::beginTransaction();

            //如果是编辑，需要把原来订单的车辆全部重置成空闲，防止有删除的车辆
            if($info['order_id']>0){
                $order = Order::query()->where('id',$info['order_id'])->first();
                CarInfo::query()->whereIn('id', explode(',', $order->car_ids))->update(['status'=>CarConstant::CAR_STATUS_FREE]);
            }

            $selectCarIds = $info['select_car_ids'];
            $selectCarnos = [];
            foreach ($selectCarIds as $selectCarId) {
                $car = CarInfo::query()->where('id',$selectCarId)->first();
                if (empty($car)) return responseFail('未查询到指定车辆！');
                $car->status = CarConstant::CAR_STATUS_BUSY;//修改车辆状态
                $car->save();
                $selectCarnos[] = $car->car_no;
            }

            $info['car_ids'] = implode(',', $info['select_car_ids']);
            $info['car_nos'] = implode(',', $selectCarnos);
            $info['car_count'] = count($info['select_car_ids']);
            $info['rent_unit_name'] = $rentUnit->unit_name;
            $info['status'] = CarConstant::ORDER_STATUS_GOING;//修改订单状态
            $info['id'] = $info['order_id'];

            unset($info['order_id']);
            unset($info['select_car_ids']);

            $order = $this->instance->updateOrCreate(['id'=>$info['id']??0],$info);
            DB::commit();
            return responseSuccess($order->toArray(),1);
        }catch (\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function backCar(Request $request){
        $orderId = $request->input('order_id');
        $back_time = $request->input('back_time');

        try {
            DB::beginTransaction();
            $order = Order::query()->where('id',$orderId)->first();
            $order->back_time = $back_time;
            $order->status = CarConstant::ORDER_STATUS_FINISHED;
            $order->save();

            //将车子置于空闲状态
            $carIds = array_filter(explode(',', $order->car_ids));
            CarInfo::query()->whereIn('id', $carIds)->update(['status'=>CarConstant::CAR_STATUS_FREE]);
            DB::commit();
            return responseSuccess([],0,'收车成功');
        }Catch(\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }

    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $record = $this->instance->getRecordById($id);
        $record->back_time = $record->back_time??date('Y-m-d H:i:s');
        return responseSuccess($record->toArray(),1);
    }

    public function change(Request $request) {
        $id = $request->input('id',0);
        $status = $request->input('status');
        $this->instance->changeColById($id, compact('status'));
        return responseSuccess();
    }

    //取消订单
    public function del(Request $request) {
        $id = $request->input('id',0);
        try {
            DB::beginTransaction();
            $order = Order::query()->where('id',$id)->first();
            //把该订单的车辆设置成空闲
            CarInfo::query()->whereIn('id',explode(',',  $order->car_ids))->update(['status'=>CarConstant::CAR_STATUS_FREE]);

            //删除订单
            $order->delete();
            DB::commit();
            return responseSuccess();
        }catch (\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }

    }
}
